package com.yb.bussiness.shoper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yb.base.dao.BaseDao;
import com.yb.base.dao.IBaseDao;
import com.yb.domain.goods.TpBuyRecord;
import com.yb.domain.member.TsSysuser;
import com.yb.util.comm.DateTimeUtil;
import com.yb.util.framework.PageUtil;

public class TpBuyRecordServiceImpl implements TpBugRecordService {
	private IBaseDao<TpBuyRecord, Long> dao;

	public TpBuyRecordServiceImpl() {
		dao = new BaseDao<TpBuyRecord, Long>(TpBuyRecord.class);
	}

	/*
	 * 查询信息 @param parameMap @return
	 */
	public List<TpBuyRecord> findByParameMap(Map<String, String> parameMap) {
		String str = " SELECT  tpbr.userId,tpbr.tel,tpbr.address,tpbr.buyNum,tpbr.proName,tpbr.model,tpbr.price,tpbr.total,tpbr.pho,tpbr.zhekou,tpbr.name,tpbr.partTime,tpbr.autding,tsm.sex sex from t_p_buy_record tpbr,t_s_member tsm  where  tpbr.userId= tsm.sysuserId";
		if (parameMap.get("brandid") != null) {
			str += " and brandId =" + parameMap.get("brandid");
		}
		if (parameMap.get("userid") != null) {
			str += " and userId =" + parameMap.get("userid");
		}
		if (parameMap.get("autding") != null) {
			str += " and autding =" + parameMap.get("autding");
		}
		str += " order by tpbr.partTime desc";
		if (parameMap.get("page") != null && parameMap.get("row") != null) {
			int start = Integer.parseInt(parameMap.get("page")) - 1;
			int limit = Integer.parseInt(parameMap.get("row"));
			str += " limit " + start * limit + "," + limit;
		}
		List<TpBuyRecord> list = dao.findList(str);
		if (list != null && !list.isEmpty()) {
			List<TpBuyRecord> newlist = new ArrayList<TpBuyRecord>();
			for (TpBuyRecord tpRecord : list) {
				// tpRecord.setQueryDateStr
				// (DateTimeUtil.switchDateToString(tpRecord.getQueryDate(),"yyyy-MM-dd
				// HH:mm:ss"));
				tpRecord.setPartTimeStr(DateTimeUtil.switchDateToString(
						tpRecord.getPartTime(), "yyyy-MM-dd HH:mm:ss"));
				newlist.add(tpRecord);
			}
			return newlist;
		}
		return null;
	}

	
	/*
     * 查询本月之后参加拼购的人员信息信息 @param parameMap @return
     */
    public List<TpBuyRecord> findByParameMap2(Map<String, String> parameMap) {
        String str = " SELECT  tpbr.userId,tpbr.tel,tpbr.address,tpbr.buyNum,tpbr.proName,tpbr.model,tpbr.price,tpbr.total,tpbr.pho,tpbr.zhekou,tpbr.name,tpbr.partTime,tpbr.autding,tsm.sex sex from t_p_buy_record tpbr,t_s_member tsm  where  tpbr.userId= tsm.sysuserId ";
        if (parameMap.get("brandid") != null) {
            str += " and brandId =" + parameMap.get("brandid");
        }
        if (parameMap.get("autding") != null) {
            str += " and autding =" + parameMap.get("autding");
        }
        str += " order by tpbr.partTime asc";
        if (parameMap.get("page") != null && parameMap.get("row") != null) {
            int start = Integer.parseInt(parameMap.get("page")) - 1;
            int limit = Integer.parseInt(parameMap.get("row"));
            str += " limit " + start * limit + "," + limit;
        }
        List<TpBuyRecord> list = dao.findList(str);
        if (list != null && !list.isEmpty()) {
            List<TpBuyRecord> newlist = new ArrayList<TpBuyRecord>();
            for (TpBuyRecord tpRecord : list) {
                // tpRecord.setQueryDateStr
                // (DateTimeUtil.switchDateToString(tpRecord.getQueryDate(),"yyyy-MM-dd
                // HH:mm:ss"));
                tpRecord.setPartTimeStr(DateTimeUtil.switchDateToString(
                        tpRecord.getPartTime(), "yyyy-MM-dd HH:mm:ss"));
                newlist.add(tpRecord);
            }
            return newlist;
        }
        return null;
    }
	
	/**
	 * 删除信息
	 * 
	 * @param ids
	 * @return
	 */
	public boolean deleteById(String ids) {
		boolean isFlag = true;
		if ("".equals(ids))
			return false;
		String sql = "";
		String[] delteid = ids.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				sql = "delete  from t_p_buy_record where  id=" + delteid[i];
				dao.delete(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return isFlag;
	}

	/**
	 * 查询总数
	 * 
	 * @param parameMap
	 * @return
	 */
	public int count(Map<String, String> parameMap) {
		try {
			String str = " SELECT  tpbr.id,tpbr.userId,tpbr.tel,tpbr.address,tpbr.buyNum,tpbr.proName,tpbr.model,tpbr.price,tpbr.total,tpbr.pho,tpbr.zhekou,tpbr.name,tpbr.partTime,tpbr.autding,tgb.sex sex from t_p_buy_record tpbr,t_g_brand tgb  where tpbr.userId=tgb.sysuserid ";
			if (parameMap.get("brandid") != null) {
				str += " and brandId =" + parameMap.get("brandid");
			}
			if (parameMap.get("userid") != null) {
				str += " and userId =" + parameMap.get("userid");
			}
			if (parameMap.get("autding") != null) {
				str += " and autding =" + parameMap.get("autding");
			}
			List<TpBuyRecord> list = dao.findList(str);
			if (list != null) {
				return list.size();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 0;
	}

	   /**
     * 查询总数
     * 
     * @param parameMap
     * @return
     */
    public int counttotal(Map<String, String> parameMap) {
        int total = 0;
        try {
            String str = " SELECT  count(tpbr.id) from t_p_buy_record tpbr where userid!=0 ";
            if (parameMap.get("brandid") != null) {
                str += " and  brandId =" + parameMap.get("brandid");
            }
            if (parameMap.get("autding") != null) {
                str += " and autding =" + parameMap.get("autding");
            }
            total = Integer
            .parseInt((dao.findObjectArryList(str).get(0))[0] + "");
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return total;
    }
	
	/**
	 * 查询某个信息
	 * 
	 * @param id
	 * @return
	 */
	public TpBuyRecord findById(String id) {
		String str = " SELECT  * FROM t_p_buy_record  WHERE id =? ";
		try {
			List<TpBuyRecord> list = dao.findList(str, new Object[] { id });
			if (list != null && !list.isEmpty()) {
				return list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return null;
	}

	/**
	 * 审核id
	 */
	public boolean updateAutingId(String id, String autding) {
		try {
			String sql = " UPDATE  t_p_buy_record t set t.autding=" + autding
					+ " WHERE t.id= " + id;
			dao.update(sql);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean saveOrUpdate(TpBuyRecord tpBuyRecord) {
		try {
			dao.saveOrUpdate(tpBuyRecord);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public int searchCountByBrandId(String brandId) {
		try {
			String sql = "SELECT userid,partTime FROM  t_p_buy_record tpbr where brandId =? AND  DATE_FORMAT(partTime,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m') and userid!=0";
			List list = dao.findList(sql, new Object[] { brandId });
			if (list != null)
				return list.size();
			return 0;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public int searchBrandCountByUserId(String brandId, String userId) {
		try {
			String sql = " SELECT  * FROM t_p_buy_record WHERE  autding =1 AND  userId= ?  AND  brandId = ?    ";
			List list = dao.findList(sql, new Object[] { userId, brandId });
			if (list != null && !list.isEmpty())
				return list.size();
			return 0;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public int count1(Map<String, String> parameMap) {
		try {
			String str = "SELECT count(tpbr.id) from t_p_buy_record tpbr,t_g_brand tgb , t_pinggou p  where tpbr.userId=tgb.sysuserid and p.brandId=tpbr.brandId ";
			if (parameMap.get("brandid") != null
					&& !"".equals(parameMap.get("brandid"))
					&& !"0".equals(parameMap.get("brandid"))) {
				str += " and tpbr.brandId =" + parameMap.get("brandid");
			}
			if (parameMap.get("userid") != null) {
				str += " and tpbr.userId =" + parameMap.get("userid");
			}
			if (parameMap.get("autding") != null) {
				str += " and tpbr.autding =" + parameMap.get("autding");
			}
			if (!"".equals(parameMap.get("categoryId"))
					&& !"0".equals(parameMap.get("categoryId"))) {
				str += " and p.categoryId =" + parameMap.get("categoryId");
			}
			if (!"".equals(parameMap.get("createTime_startTime")))
				if (!"".equals(parameMap.get("createTime_endTime")))
					str += "  AND CAST(tpbr.createTime AS DATETIME) BETWEEN CAST('"
							+ parameMap.get("createTime_startTime")
							+ "' AS DATETIME) AND CAST('"
							+ parameMap.get("createTime_endTime")
							+ "' AS DATETIME)";
				else
					str += "  and tpbr.createTime>='"
							+ parameMap.get("createTime_startTime") + "'";
			else if (!"".equals(parameMap.get("createTime_endTime")))
				str += "  and tpbr.createTime<='"
						+ parameMap.get("createTime_endTime") + "'";

			if (!"".equals(parameMap.get("partTime_startTime")))
				if (!"".equals(parameMap.get("partTime_endTime")))
					str += "  AND CAST(tpbr.partTime AS DATETIME) BETWEEN CAST('"
							+ parameMap.get("partTime_startTime")
							+ "' AS DATETIME) AND CAST('"
							+ parameMap.get("partTime_endTime")
							+ "' AS DATETIME)";
				else
					str += "  and tpbr.partTime>='"
							+ parameMap.get("partTime_startTime") + "'";
			else if (!"".equals(parameMap.get("partTime_endTime")))
				str += "  and tpbr.partTime<='"
						+ parameMap.get("partTime_endTime") + "'";
			List list = dao.findObjectArryList(str);
			Object[] obj = (Object[]) list.get(0);
			return new Integer(obj[0].toString());
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public List<TpBuyRecord> findByParameMap1(Map<String, String> parameMap) {
		String str = " SELECT  tpbr.*,tgb.sex sex from t_p_buy_record tpbr,t_g_brand tgb , t_pinggou p  where tpbr.userId=tgb.sysuserid and p.brandId=tpbr.brandId ";
		if (parameMap.get("brandid") != null
				&& !"".equals(parameMap.get("brandid"))
				&& !"0".equals(parameMap.get("brandid"))) {
			str += " and tpbr.brandId =" + parameMap.get("brandid");
		}
		if (parameMap.get("userid") != null) {
			str += " and tpbr.userId =" + parameMap.get("userid");
		}
		if (parameMap.get("autding") != null) {
			str += " and tpbr.autding =" + parameMap.get("autding");
		}
		if (!"".equals(parameMap.get("categoryId"))
				&& !"0".equals(parameMap.get("categoryId"))) {
			str += " and p.categoryId =" + parameMap.get("categoryId");
		}
		if (!"".equals(parameMap.get("createTime_startTime")))
			if (!"".equals(parameMap.get("createTime_endTime")))
				str += "  AND CAST(tpbr.createTime AS DATETIME) BETWEEN CAST('"
						+ parameMap.get("createTime_startTime")
						+ "' AS DATETIME) AND CAST('"
						+ parameMap.get("createTime_endTime")
						+ "' AS DATETIME)";
			else
				str += "  and tpbr.createTime>='"
						+ parameMap.get("createTime_startTime") + "'";
		else if (!"".equals(parameMap.get("createTime_endTime")))
			str += "  and tpbr.createTime<='"
					+ parameMap.get("createTime_endTime") + "'";

		if (!"".equals(parameMap.get("partTime_startTime")))
			if (!"".equals(parameMap.get("partTime_endTime")))
				str += "  AND CAST(tpbr.partTime AS DATETIME) BETWEEN CAST('"
						+ parameMap.get("partTime_startTime")
						+ "' AS DATETIME) AND CAST('"
						+ parameMap.get("partTime_endTime") + "' AS DATETIME)";
			else
				str += "  and tpbr.partTime>='"
						+ parameMap.get("partTime_startTime") + "'";
		else if (!"".equals(parameMap.get("partTime_endTime")))
			str += "  and tpbr.partTime<='" + parameMap.get("partTime_endTime")
					+ "'";
		str += " order by tpbr.createTime desc ";
		if (parameMap.get("page") != null && parameMap.get("row") != null) {
			int start = Integer.parseInt(parameMap.get("page")) - 1;
			int limit = Integer.parseInt(parameMap.get("row"));
			str += " limit " + start * limit + "," + limit;
		}
		List<TpBuyRecord> list = dao.findList(str);
		if (list != null && !list.isEmpty()) {
			List<TpBuyRecord> newlist = new ArrayList<TpBuyRecord>();
			for (TpBuyRecord tpRecord : list) {
				tpRecord.setPartTimeStr(DateTimeUtil.switchDateToString(
						tpRecord.getPartTime(), "yyyy-MM"));
				tpRecord.setCreateTimeStr(DateTimeUtil.switchDateToString(
						tpRecord.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				newlist.add(tpRecord);
			}
			return newlist;
		}
		return null;
	}

	public Map<String, Object> searchpinggourecord(Map<String, String> parameMap) {
		String sql = "select tgb.name brandName,tpbr.* from t_p_buy_record tpbr left join t_g_brand tgb on tpbr.brandId = tgb.id  where 1=1 ";//exists ( select 1 from t_s_member tsm  where tpbr.userId = tsm.sysuserId) ";
		String countSql = "select count(*) from t_p_buy_record tpbr left join t_g_brand tgb on tpbr.brandId = tgb.id where 1=1 ";//exists ( select 1 from t_s_member tsm  where tpbr.userId = tsm.sysuserId)  ";

		if (parameMap != null) {
			if (parameMap.get("brandName") != null
					&& !"".equals(parameMap.get("brandName"))) {
				sql += " and tgb.name like '%" + parameMap.get("brandName")
						+ "%' ";
				countSql += " and tgb.name like '%"
						+ parameMap.get("brandName") + "%' ";
			}
			if (parameMap.get("autding") != null
					&& !"".equals(parameMap.get("autding"))) {
				if("00".equals(parameMap.get("autding"))){
					sql += " and tpbr.userId = 0 ";
					countSql += " and tpbr.userId = 0";
				}else if("000".equals(parameMap.get("autding"))){
					sql += " and tpbr.autding = " + parameMap.get("autding");
					countSql += " and tpbr.autding = " + parameMap.get("autding");
				}else{
					sql += " and tpbr.userId != 0 and tpbr.autding = " + parameMap.get("autding");
					countSql += " and tpbr.userId != 0 and tpbr.autding = " + parameMap.get("autding");
				}
			}
			if (!"0".equals(parameMap.get("categoryId"))) {

				sql += " AND EXISTS (SELECT 1 FROM t_brand_type tbt LEFT JOIN  t_g_category tgc ON tbt.categoryId = tgc.id  WHERE tbt.brandId=tpbr.brandId AND tgc.pID = "
						+ parameMap.get("categoryId") + ")";
				countSql += " AND EXISTS (SELECT 1 FROM t_brand_type tbt LEFT JOIN  t_g_category tgc ON tbt.categoryId = tgc.id  WHERE tbt.brandId=tpbr.brandId AND tgc.pID = "
						+ parameMap.get("categoryId") + ")";
			}

			if (parameMap.get("createTime_startTime") != null
					&& !"".equals(parameMap.get("createTime_startTime"))) {
				sql += " and tpbr.createTime >= '"
						+ parameMap.get("createTime_startTime") + " 00:00:00'";
				countSql += " and tpbr.createTime >= '"
						+ parameMap.get("createTime_startTime") + " 00:00:00'";
			}
			if (parameMap.get("createTime_endTime") != null
					&& !"".equals(parameMap.get("createTime_endTime"))) {
				sql += " and tpbr.createTime <= '"
						+ parameMap.get("createTime_endTime") + " 23:59:59'";
				countSql += " and tpbr.createTime <= '"
						+ parameMap.get("createTime_endTime") + " 23:59:59'";
			}
			if (parameMap.get("partTime_startTime") != null
					&& !"".equals(parameMap.get("partTime_startTime"))) {
				sql += " and tpbr.partTime >= '"
						+ parameMap.get("partTime_startTime") + "01 00:00:00'";
				countSql += " and tpbr.partTime >= '"
						+ parameMap.get("partTime_startTime") + "01 00:00:00'";
			}
			if (parameMap.get("partTime_endTime") != null
					&& !"".equals(parameMap.get("partTime_endTime"))) {
				sql += " and tpbr.partTime <= '"
						+ parameMap.get("partTime_endTime") + "01 23:59:59'";
				countSql += " and tpbr.partTime <= '"
						+ parameMap.get("partTime_endTime") + "01 23:59:59'";
			}
		}
		if (parameMap.get("page") != null && parameMap.get("row") != null) {
			int start = Integer.parseInt(parameMap.get("page")) - 1;
			int limit = Integer.parseInt(parameMap.get("row"));
			sql += "  order by tpbr.id  desc limit  " + (start * limit) + ","
					+ limit + " ";
		}
		List<TpBuyRecord> list = dao.findList(sql);
		List<TpBuyRecord> newlist = new ArrayList<TpBuyRecord>();
		if (list != null && !list.isEmpty()) {
			for (TpBuyRecord tpRecord : list) {
				tpRecord.setPartTimeStr(DateTimeUtil.switchDateToString(
						tpRecord.getPartTime(), "yyyy-MM-dd HH:mm:ss"));
				tpRecord.setCreateTimeStr(DateTimeUtil.switchDateToString(
						tpRecord.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				newlist.add(tpRecord);
			}
		}

		int total = 0;
		if (list.size() != 0) {
			total = Integer
					.parseInt((dao.findObjectArryList(countSql).get(0))[0] + "");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", newlist);
		map.put("total", total);
		return map;
	}

	public PageUtil getList(Map<String, String> map, int start, int limit) {
		PageUtil pu = new PageUtil();
		String find_sql = "SELECT tpbr.*,tgb.name brandName FROM t_p_buy_record tpbr,t_g_brand tgb  WHERE tpbr.brandId=tgb.id ";
		String countSql = "SELECT COUNT(tpbr.id) FROM t_p_buy_record tpbr,t_g_brand tgb  WHERE tpbr.brandId=tgb.id ";
		try {
			if (null != map.get("userid") && !"".equals(map.get("userid"))) {
				find_sql += " AND tpbr.userId = '" + map.get("userid") + "'";
				countSql += " AND tpbr.userId = '" + map.get("userid") + "'";
			}
			List<Object[]> countList = dao.findObjectArryList(countSql
					.toString());
			List<TpBuyRecord> newlist = null;
			if (null != countList && countList.size() > 0) {
				Object[] countAry = countList.get(0);
				pu.setTotalRecords(new Integer(countAry[0].toString()));
				List<TpBuyRecord> list = dao.findList(find_sql
						+ " ORDER BY createTime desc limit ?,?", new Object[] {
						(start - 1) * limit, limit });
				if (list != null && list.size() > 0) {
					newlist = new ArrayList<TpBuyRecord>();
					for (TpBuyRecord tp : list) {
						if (null != tp.getCreateTime())
							tp.setCreateTimeStr(DateTimeUtil
									.switchDateToString(tp.getCreateTime(),
											"yyyy-MM-dd HH:mm:ss"));
						if (null != tp.getPartTime())
							tp.setPartTimeStr(DateTimeUtil.switchDateToString(
									tp.getPartTime(), "yyyy年MM月"));
						newlist.add(tp);
					}
				}
			} else {
				pu.setTotalRecords(0);
			}
			if (null == newlist)
				newlist = new ArrayList<TpBuyRecord>();
			pu.setList(newlist);
			pu.setPageNo(start);
			pu.setPageSize(limit);
			return pu;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Integer loadpinggourecord() {
		String sql = "select count(1) from t_p_buy_record tpbr left join t_g_brand tgb on tpbr.brandId = tgb.id  where tpbr.autding = 0 ";
		int total = Integer.parseInt((dao.findObjectArryList(sql).get(0))[0]
				.toString());
		return total;
	}

	public List<TpBuyRecord> loadByTime(String time) {
		String sql = "SELECT * FROM t_p_buy_record where createTime > '" + time
				+ "'";
		return dao.findList(sql);
	}
}
